import type { DirectiveBinding, ObjectDirective } from 'vue';

interface MenuItem {
  text: string;
  action: () => void;
}

/**
 * 右键菜单指令
 */
const rightClickMenuDirective: ObjectDirective<any, MenuItem[]> = {
  mounted(el, binding) {
    const menu = document.createElement('div');
    menu.classList.add('click-menu');
    console.log(binding);
    
    const menuItems = binding.value;

    menuItems.forEach((item) => {
      const menuItem = document.createElement('div');
      menuItem.innerText = item.text;
      menuItem.addEventListener('click', item.action);
      menu.appendChild(menuItem);
    });

    el.addEventListener('contextmenu', (event: MouseEvent) => {
      event.preventDefault();

      menu.style.left = `${event.clientX}px`;
      menu.style.top = `${event.clientY}px`;

      document.body.appendChild(menu);

      const handleGlobalClick = () => {
        document.body.removeChild(menu);
        document.removeEventListener('click', handleGlobalClick);
      };

      document.addEventListener('click', handleGlobalClick);
    });
  },
};

export default rightClickMenuDirective